package primetest.impl.dictionary;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

import primetest.dto.TermDto;
import primetest.impl.dictionary.Dictionary;
import primetest.impl.service.TermService;

@Named
@SessionScoped
public class Dictionary implements Map<String, String>, Serializable {

	private static final long serialVersionUID = 842658217049435641L;

	private Map<String, String> innerMap;


	private TermService termService;

	public Dictionary() {

	}

	@Inject
	public Dictionary(TermService termService)
			throws IOException {
		innerMap = new HashMap<String, String>();
		for (TermDto t : termService.getTermList()) {
			innerMap.put(t.getKey(), t.getValue());
		}
		this.termService = termService;
	}

	public String get(Object key) {
		return get((String) key);
	}

	public int size() {
		return innerMap.size();
	}

	public boolean isEmpty() {
		return innerMap.isEmpty();
	}

	public boolean containsKey(Object key) {
		return innerMap.containsKey(key);
	}

	public boolean containsValue(Object value) {
		return innerMap.containsValue(value);
	}

	public String remove(Object key) {
		return innerMap.remove(key);
	}

	public void putAll(Map<? extends String, ? extends String> m) {
		innerMap.putAll(m);
	}

	public Set<String> keySet() {
		return innerMap.keySet();
	}

	public Collection<String> values() {
		return innerMap.values();
	}

	public Set<java.util.Map.Entry<String, String>> entrySet() {
		return innerMap.entrySet();
	}

	public String get(String key)  {
		String value = innerMap.get(key);
		if (value == null) {
			value = key;
			try {
				termService.addTerm(new TermDto(key, value));
				innerMap.put(key, value);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return value;
	}

	public String put(String key, String value) {
		if (innerMap.get(key) != value) {
			try {
				termService.updateTerm(new TermDto(key, value));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return innerMap.put(key, value);
	}

	public void clear() {
		innerMap.clear();
	}
}
